import * as React from 'react'
import { View, Text, StyleSheet, Platform, Modal, StatusBar, TouchableOpacity, Animated, Easing } from 'react-native'


import { px2dp, deviceWidth } from '../../../screen/px2dp'
import { px2sp } from '../../../screen/px2sp'

import { AlertViewOptions } from '.'



type State = {
    visible: boolean;

} & Omit<AlertViewOptions, 'cancel' | 'confirm'>





export default React.forwardRef<AlertViewOptions.RefAttributes, {}>((_, ref) => {


    const defaultState: Partial<State> = {
        visible: false,
        cancelText: '取消',
        confirmText: '确定',
    }
    const [state, setState] = React.useState<Partial<State>>(defaultState)
    const cancelCallbackRef = React.useRef<Function>();
    const confirmCallbackRef = React.useRef<Function>();


    
    React.useImperativeHandle<unknown, AlertViewOptions.RefAttributes>(ref, () => ({
        show: async (options: Partial<AlertViewOptions>) => {

            setState(Object.assign({}, defaultState, { visible: true }, options))
            cancelCallbackRef.current = options.cancel;
            confirmCallbackRef.current = options.confirm;
            // await sleep(50)
            startAnimate(1)
        },
        hide
    }), [])


    const hide = async () => {
        startAnimate(0.3)
        // await sleep(50)
        setState(defaultState)

    }

    let scale_anim = React.useRef(new Animated.Value(0.3)).current
    const startAnimate = (x: number) => {
        Animated.timing(scale_anim, {
            toValue: x,
            useNativeDriver: true,
            duration: 150,
            easing: Easing.ease
        }).start()
    }
    React.useEffect(() => {
        if (Platform.OS == 'android') {
            if (state.visible) {
                StatusBar.setBackgroundColor('black')
                StatusBar.setBarStyle('light-content')
            } else {
                StatusBar.setBackgroundColor('transparent')
                StatusBar.setBarStyle('dark-content')
            }
        }

    }, [state.visible])
    return (
        <Modal
            visible={state.visible}
            transparent animationType="fade"
            onRequestClose={() => {
                // hide()
            }}
        // style={{
        //     margin: 0,
        // }}
        >
            <View style={styles.container}>
                <Animated.View style={[styles.wrapper, state.wrapperStyle, { transform: [{ scale: scale_anim }] }]}>
                    {state.title && <Text style={styles.titleText}>{state.title}</Text>}
                    {(() => {
                        if (typeof state.content == 'string') return <Text style={styles.contentText}>{state.content}</Text>
                        if (React.isValidElement(state.content)) return state.content;
                        return <View />
                    })()}

                    {
                        (state.cancelText || state.confirmText) &&
                        <View style={styles.action}>
                            {state.cancelText &&
                                <TouchableOpacity
                                    style={[styles.cancel, { marginRight: state.confirmText ? px2dp(15) : 0 }, state.cancelContainerStyle]}
                                    activeOpacity={0.8}
                                    disabled={state.cancelDisabled}
                                    onPress={() => {
                                        hide()
                                        cancelCallbackRef.current && cancelCallbackRef.current()
                                        cancelCallbackRef.current = undefined;

                                    }}>
                                    <Text style={[styles.cancelText, state.cancelTextStyle]}>{state.cancelText}</Text>
                                </TouchableOpacity>
                            }

                            {state.confirmText &&
                                <TouchableOpacity
                                    style={[styles.confirm, { marginLeft: state.cancelText ? px2dp(15) : 0 }, state.confirmContainerStyle]}
                                    activeOpacity={0.8}
                                    onPress={() => {
                                        hide()
                                        confirmCallbackRef.current && confirmCallbackRef.current()
                                        confirmCallbackRef.current = undefined;
                                    }}>
                                    <Text style={[styles.confirmText, state.confirmTextStyle]}>{state.confirmText}</Text>
                                </TouchableOpacity>
                            }
                        </View>
                    }

                </Animated.View>

            </View>
        </Modal>
    )
})



export const alertViewRef = React.createRef<AlertViewOptions.RefAttributes>();



export const showAlertModal = (props: Partial<AlertViewOptions>) => {
    alertViewRef.current?.show(props)
}



// const sleep = (msec?: number) => {
//     return new Promise(resolve => {
//         setTimeout(resolve, msec || 350);
//     });
// }



const styles = StyleSheet.create({
    container: {
        display: 'flex',
        flexGrow: 1,
        backgroundColor: '#00000088',
        justifyContent: 'center',
        alignItems: 'center',

    },

    wrapper: {
        flexGrow: 0,
        flexShrink: 0,
        // minWidth: '70%',
        minWidth: deviceWidth - px2dp(60),
        backgroundColor: 'white',
        overflow: 'hidden',
        borderRadius: px2dp(10),
        display: 'flex',
        padding: px2dp(15),
    },
    titleText: {
        maxWidth: deviceWidth - px2dp(90),
        fontSize: px2sp(18),
        marginBottom: px2dp(20),
        // backgroundColor: 'red',
        textAlign: 'center',
        fontWeight: 'bold',
        color: '#1A1A1A'
    },
    contentText: {
        maxWidth: deviceWidth - px2dp(90),
        marginBottom: px2dp(20),
        minHeight: px2dp(40),
        flexGrow: 0,
        flexShrink: 1,
        width: undefined,
        fontSize: px2sp(15),
        // backgroundColor: 'red',
        color: '#1A1A1A',
        textAlign: 'center'
    },
    action: {
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        // backgroundColor:"red"
    },
    cancel: {
        width: '40%',
        height: px2dp(44),
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: px2dp(10),
        borderWidth: px2dp(1),
        borderColor: '#A3A9CC'
    },

    confirm: {
        width: '40%',
        height: px2dp(44),
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#2763FF',
        borderRadius: px2dp(10)
    },
    cancelText: {
        fontSize: px2sp(15),
        color: '#A3A9CC',

    },
    confirmText: {
        fontSize: px2sp(15),
        color: 'white'
    },
})